package com.cc.gateway.authorization;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.cc.gateway.constant.AuthConstant;
import com.cc.gateway.constant.RedisConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpMethod;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.authorization.ReactiveAuthorizationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.server.authorization.AuthorizationContext;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 鉴权管理器，用于判断是否有资源的访问权限
 * Created by macro on 2020/6/19.
 */
@Component
@Slf4j
public class AuthorizationManager implements ReactiveAuthorizationManager<AuthorizationContext> {
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Override
    public Mono<AuthorizationDecision> check(Mono<Authentication> mono, AuthorizationContext authorizationContext) {
        ServerHttpRequest request = authorizationContext.getExchange().getRequest();
        String path = request.getURI().getPath();
        // 1. 对应跨域的预检请求直接放行
        if (request.getMethod() == HttpMethod.OPTIONS) {
            return Mono.just(new AuthorizationDecision(true));
        }

        // 2. token为空拒绝访问
        String token = request.getHeaders().getFirst(AuthConstant.JWT_TOKEN_HEADER);
        if (StrUtil.isBlank(token)) {
            return Mono.just(new AuthorizationDecision(false));
        }


        //3.从Redis中获取当前路径可访问角色列表
        URI uri = request.getURI();
        Object obj = redisTemplate.opsForHash().get(RedisConstant.RESOURCE_ROLES_MAP, uri.getPath());
        List<String> authorities = Convert.toList(String.class,obj);
        authorities = authorities.stream().map(i -> i = AuthConstant.AUTHORITY_PREFIX + i).collect(Collectors.toList());
        //4.认证通过且角色匹配的用户可访问当前路径
        //List<String> finalAuthorities = authorities;
        return mono
                //过来认证的用户
                .filter(Authentication::isAuthenticated)
                //获取认证用户的权限列表
                .flatMapIterable(Authentication::getAuthorities)
                //获取每个权限的权限名称
                .map(GrantedAuthority::getAuthority)
                //与redis中用户的权限配置
                .any(authorities::contains)
                //.any(roleId -> {
                //    // 5. roleId是请求用户的角色(格式:ROLE_{roleId})，authorities是请求资源所需要角色的集合
                //    log.info("访问路径：{}", path);
                //    log.info("用户角色roleId：{}", roleId);
                //    log.info("资源需要权限authorities：{}", finalAuthorities);
                //    return finalAuthorities.contains(roleId);
                //})
                //匹配的用户构建AuthorizationDecision 默认授权通过
                .map(AuthorizationDecision::new)
                //不配置的用户构建AuthorizationDecision 权限不通过
                .defaultIfEmpty(new AuthorizationDecision(false));
    }

}
